package com.mchsdk.paysdk.http;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.lidroid.xutils.http.ResponseInfo;
import com.mchsdk.paysdk.config.MCHConstant;
import com.mchsdk.paysdk.utils.Base64;
import com.mchsdk.paysdk.utils.Base64Util;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.ToastUtil;
/**
 * 将参数排序，加密
 */
public class RequestParamUtil {

	private static final String TAG = "RequestParamUtil";
	/**
	 *拼接请求参数 将参数排序，加密
	 */
	public static String getRequestParamString(Map<String, String> paramMap) {
		if (null == paramMap || paramMap.size() < 1) {
			return "";
		}
		//将map按照键值排序
		List<Map.Entry<String, String>> mappingList = new ArrayList<Map.Entry<String, String>>(
				paramMap.entrySet());
		Collections.sort(mappingList,
				new Comparator<Map.Entry<String, String>>() {

					@Override
					public int compare(Map.Entry<String, String> mapping1,
							Map.Entry<String, String> mapping2) {
						return mapping1.getKey().compareTo(mapping2.getKey());
					}
				});
	    //将map和验签的sign添加到请求参数里面
		JSONObject jsonparam = new JSONObject();
		String values = "";
		try {
			for (Map.Entry<String, String> mapping : mappingList) {
				String key = mapping.getKey().trim();
				String value = mapping.getValue();
				//向JSONObject对象中添加请求参数
				jsonparam.put(key, value);
				//拼接排序后的value值
				values += mapping.getValue();
			}
//			MCLog.i(TAG, "key " + KEY.signKey);
			//生成验签字符串
//			String md5key = KEY.stringToMD5(values.trim() + KEY.signKey);
			String md5key = KEY.stringToMD5(values.trim() + MCHConstant.getInstance().getMCHKEY());
			//将验签字符串添加到参数中
			jsonparam.put("md5_sign", md5key);
			MCLog.i(TAG, "发送的参数" + jsonparam.toString());
			//对参数base64处理防止中文乱码
			return Base64.encode(jsonparam.toString().getBytes());
		} catch (JSONException e) {
			return "";
		}
	}
	/**或得返回内容*/
	public static String Result(ResponseInfo<String> responseInfo){
		String result = responseInfo.result.trim().replaceAll(" ", "");
		try {
			MCLog.i(TAG,"请求响应"+result);
			result= new String(Base64.decode(result), "utf-8");
		} catch (Exception e1) {
			MCLog.i(TAG,"第一次解码出错");
			result = Base64Util.getDecodeStr(result);
		}finally{
			try {
				JSONObject object=new JSONObject(result);
				MCLog.i(TAG,"请求响应"+result+object.optString("return_msg"));
			} catch (JSONException e) {
				MCLog.i(TAG,"请求响应"+result);
			}
		}
		
		return result;
	}
	/**获得返回码*/
	public static int ResultCode(Post post){
		if(null==post){
			return 0;
		}
		return post.getCode();
	}
}
